package com.lxs.doc.rocess.common2;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class WordOutlineParser {
    /**
     * 大纲项实体类
     */
    static class OutlineItem {
        private int level;
        private String text;

        public OutlineItem(int level, String text) {
            this.level = level;
            this.text = text;
        }

        public int getLevel() {
            return level;
        }

        public String getText() {
            return text;
        }

        @Override
        public String toString() {
            return "Level " + level + ": " + text;
        }
    }
        /**
         * 根据文件路径解析Word文档大纲
         *
         * @param filePath 文件路径
         * @return 大纲列表
         */
        public List<OutlineItem> parseOutline(String filePath) {
            File file = new File(filePath);
            if (!file.exists()) {
                System.err.println("文件不存在: " + filePath);
                return null;
            }

            String fileName = file.getName();
            if (fileName.endsWith(".docx")) {
                return parseDocxOutline(filePath);
            } else if (fileName.endsWith(".doc")) {
                return parseDocOutline(filePath);
            } else {
                System.err.println("不支持的文件格式，仅支持.doc和.docx");
                return null;
            }
        }

        /**
         * 解析docx文档大纲
         *
         * @param docxPath docx文件路径
         * @return 大纲列表
         */
        private List<OutlineItem> parseDocxOutline(String docxPath) {
            List<OutlineItem> outline = new ArrayList<>();

            try (XWPFDocument document = new XWPFDocument(new FileInputStream(docxPath))) {
                for (XWPFParagraph paragraph : document.getParagraphs()) {
                    String styleName = paragraph.getStyle();
                    if (styleName != null && styleName.startsWith("Heading")) {
                        try {
                            // 从样式名称中提取标题级别 (例如 "Heading1" -> 1)
                            int level = Integer.parseInt(styleName.replace("Heading", ""));
                            String text = paragraph.getText().trim();

                            if (!text.isEmpty()) {
                                outline.add(new OutlineItem(level, text));
                            }
                        } catch (NumberFormatException e) {
                            // 忽略无法解析级别的标题样式
                        }
                    }
                }
            } catch (IOException e) {
                System.err.println("解析docx文件时出错: " + e.getMessage());
            }

            return outline;
        }

        /**
         * 解析doc文档大纲
         *
         * @param docPath doc文件路径
         * @return 大纲列表
         */
        private List<OutlineItem> parseDocOutline(String docPath) {
            List<OutlineItem> outline = new ArrayList<>();

            try (HWPFDocument document = new HWPFDocument(new FileInputStream(docPath))) {
                Range range = document.getRange();

//                for (int i = 0; i < range.numParagraphs(); i++) {
//                    Paragraph paragraph = range.getParagraph(i);
//                    String styleName = paragraph.getName();
//
//                    // 检查是否是标题样式
//                    if (styleName != null && (styleName.startsWith("Heading") || styleName.startsWith("标题"))) {
//                        try {
//                            // 提取标题级别
//                            int level = 0;
//                            for (char c : styleName.toCharArray()) {
//                                if (Character.isDigit(c)) {
//                                    level = Character.getNumericValue(c);
//                                    break;
//                                }
//                            }
//
//                            if (level > 0) {
//                                String text = paragraph.text().trim();
//                                if (!text.isEmpty()) {
//                                    outline.add(new OutlineItem(level, text));
//                                }
//                            }
//                        } catch (Exception e) {
//                            // 忽略解析错误的标题
//                        }
//                    }
//                }
            } catch (IOException e) {
                System.err.println("解析doc文件时出错: " + e.getMessage());
            }

            return outline;
        }

        /**
         * 打印大纲结构
         *
         * @param outline 大纲列表
         */
        public void printOutline(List<OutlineItem> outline) {
            if (outline == null || outline.isEmpty()) {
                System.out.println("未提取到大纲内容");
                return;
            }

            System.out.println("文档大纲:");
            for (OutlineItem item : outline) {
                // 根据级别生成缩进
                StringBuilder indent = new StringBuilder();
                for (int i = 1; i < item.getLevel(); i++) {
                    indent.append("  ");
                }
                System.out.println(indent + item.toString());
            }
        }

        /**
         * 主方法，示例用法
         */
        public static void main(String[] args) {
            WordOutlineParser parser = new WordOutlineParser();
            // 替换为实际的Word文档路径
            String filePath = "example.docx";
            // String filePath = "example.doc";

            List<OutlineItem> outline = parser.parseOutline(filePath);
            parser.printOutline(outline);
        }
}
